import axios from "axios";
import { useUserStore } from '@/stores/user'
import { message as AntMessage } from 'ant-design-vue';
import {useSysStore} from '@/stores/sys'
import { refreshToken ,isRefreshRequest} from '@/api/login';
import router from '@/router'

const request = axios.create({
    baseURL: "/api", // 在所有的请求前面加上api前缀
    timeout: 5000
});

// 请求拦截器
request.interceptors.request.use((config) => {
    const userStore = useUserStore();
    const token = userStore.token;
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }

    if (/get/i.test(config.method)) { // 判断get请求
        config.params = config.params || {};
        config.params.t = new Date().valueOf(); // 添加时间戳
    }

    if(config.url!="influx/demo"){
        showLoading();
    }

    return config;
}, (error) => {
    hideLoading();
    return Promise.reject(error)
});

// 响应拦截器
request.interceptors.response.use( async (response) => {
    const { code, message } = response.data;

    if (response.config.responseType === 'blob') {
        // 处理文件下载请求
        if (response.status === 200) {
            hideLoading();
            return response; // 直接返回响应
        }
    } else if (code === 200) {
        hideLoading();
        return response.data;
    }

    hideLoading();
    if (code === 401) {
        AntMessage.error({
            content: () => message,
            style: {
                marginTop: '20vh',
            },
        });
        return router.push("/login");
    } else {
        AntMessage.error(message);
    }
}, (error) => {
    hideLoading();
    return Promise.reject(error);
});

let loadCount=0;
const showLoading=()=>{
    const sysStore = useSysStore()
    if(loadCount===0){
        sysStore.openSpin()
    }
    loadCount++;
}

const hideLoading=()=>{
    const sysStore = useSysStore()
    loadCount--
    if(loadCount===0){
        sysStore.closeSpin()
    }
}

export default request;